#!/usr/bin/env python3
"""
模拟应用程序
生成HTTP请求指标和自定义业务指标
"""

import time
import random
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class AppMetricsHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        self.request_count = 0
        self.error_count = 0
        super().__init__(*args, **kwargs)
    
    def do_GET(self):
        self.request_count += 1
        
        if self.path == '/metrics':
            self.send_response(200)
            self.send_header('Content-type', 'text/plain; version=0.0.4; charset=utf-8')
            self.end_headers()
            
            metrics = self.generate_app_metrics()
            self.wfile.write(metrics.encode('utf-8'))
        
        elif self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            
            html = """
            <html>
            <head><title>Mock Application</title></head>
            <body>
                <h1>Mock Application</h1>
                <p>模拟的业务应用程序</p>
                <p><a href="/metrics">查看应用指标</a></p>
                <p><a href="/api/users">用户API</a></p>
                <p><a href="/api/orders">订单API</a></p>
                <p><a href="/health">健康检查</a></p>
                <p>端口: 8080</p>
            </body>
            </html>
            """
            self.wfile.write(html.encode('utf-8'))
        
        elif self.path == '/api/users':
            # 模拟用户API
            if random.random() < 0.1:  # 10% 错误率
                self.send_response(500)
                self.error_count += 1
            else:
                self.send_response(200)
            
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            users = [
                {"id": 1, "name": "张三", "email": "zhangsan@example.com"},
                {"id": 2, "name": "李四", "email": "lisi@example.com"},
                {"id": 3, "name": "王五", "email": "wangwu@example.com"}
            ]
            self.wfile.write(json.dumps(users, ensure_ascii=False).encode('utf-8'))
        
        elif self.path == '/api/orders':
            # 模拟订单API
            if random.random() < 0.05:  # 5% 错误率
                self.send_response(500)
                self.error_count += 1
            else:
                self.send_response(200)
            
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            orders = [
                {"id": 1001, "user_id": 1, "amount": 299.99, "status": "completed"},
                {"id": 1002, "user_id": 2, "amount": 159.50, "status": "pending"},
                {"id": 1003, "user_id": 3, "amount": 89.00, "status": "shipped"}
            ]
            self.wfile.write(json.dumps(orders, ensure_ascii=False).encode('utf-8'))
        
        elif self.path == '/health':
            # 健康检查端点
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            health = {
                "status": "healthy",
                "timestamp": time.time(),
                "uptime": time.time() - start_time,
                "version": "1.0.0"
            }
            self.wfile.write(json.dumps(health).encode('utf-8'))
        
        else:
            self.send_response(404)
            self.end_headers()
    
    def generate_app_metrics(self):
        """生成应用程序指标"""
        current_time = time.time()
        
        # 模拟业务指标
        active_users = random.randint(50, 200)
        orders_per_minute = random.randint(10, 50)
        revenue_total = random.uniform(10000, 50000)
        database_connections = random.randint(5, 20)
        cache_hit_rate = random.uniform(0.8, 0.95)
        
        metrics = f"""# HELP app_http_requests_total Total number of HTTP requests
# TYPE app_http_requests_total counter
app_http_requests_total{{method="GET",endpoint="/api/users",status="200"}} {random.randint(1000, 5000)}
app_http_requests_total{{method="GET",endpoint="/api/users",status="500"}} {random.randint(10, 100)}
app_http_requests_total{{method="GET",endpoint="/api/orders",status="200"}} {random.randint(800, 3000)}
app_http_requests_total{{method="GET",endpoint="/api/orders",status="500"}} {random.randint(5, 50)}
app_http_requests_total{{method="GET",endpoint="/health",status="200"}} {random.randint(500, 1000)}

# HELP app_http_request_duration_seconds HTTP request duration in seconds
# TYPE app_http_request_duration_seconds histogram
app_http_request_duration_seconds_bucket{{endpoint="/api/users",le="0.1"}} {random.randint(800, 900)}
app_http_request_duration_seconds_bucket{{endpoint="/api/users",le="0.5"}} {random.randint(950, 980)}
app_http_request_duration_seconds_bucket{{endpoint="/api/users",le="1.0"}} {random.randint(990, 995)}
app_http_request_duration_seconds_bucket{{endpoint="/api/users",le="+Inf"}} 1000
app_http_request_duration_seconds_sum{{endpoint="/api/users"}} {random.uniform(100, 500)}
app_http_request_duration_seconds_count{{endpoint="/api/users"}} 1000

# HELP app_active_users Current number of active users
# TYPE app_active_users gauge
app_active_users {active_users}

# HELP app_orders_per_minute Orders processed per minute
# TYPE app_orders_per_minute gauge
app_orders_per_minute {orders_per_minute}

# HELP app_revenue_total Total revenue in dollars
# TYPE app_revenue_total counter
app_revenue_total {revenue_total}

# HELP app_database_connections Current database connections
# TYPE app_database_connections gauge
app_database_connections {database_connections}

# HELP app_cache_hit_rate Cache hit rate
# TYPE app_cache_hit_rate gauge
app_cache_hit_rate {cache_hit_rate}

# HELP app_memory_usage_bytes Application memory usage in bytes
# TYPE app_memory_usage_bytes gauge
app_memory_usage_bytes {random.randint(100000000, 500000000)}

# HELP app_cpu_usage_percent Application CPU usage percentage
# TYPE app_cpu_usage_percent gauge
app_cpu_usage_percent {random.uniform(10, 80)}

# HELP app_error_rate Application error rate
# TYPE app_error_rate gauge
app_error_rate {random.uniform(0.01, 0.1)}

# HELP app_response_time_p95 95th percentile response time
# TYPE app_response_time_p95 gauge
app_response_time_p95 {random.uniform(0.1, 2.0)}

# HELP app_queue_size Current queue size
# TYPE app_queue_size gauge
app_queue_size {random.randint(0, 100)}

# HELP app_uptime_seconds Application uptime in seconds
# TYPE app_uptime_seconds counter
app_uptime_seconds {current_time - start_time}

# HELP up Was the last scrape of the target successful
# TYPE up gauge
up 1
"""
        return metrics
    
    def log_message(self, format, *args):
        """禁用默认日志输出"""
        pass

# 记录启动时间
start_time = time.time()

def run_app():
    """运行模拟应用程序"""
    server = HTTPServer(('0.0.0.0', 8080), AppMetricsHandler)
    print("🚀 Mock Application 启动成功，监听端口 8080")
    print("📊 指标端点: http://localhost:8080/metrics")
    print("🌐 应用首页: http://localhost:8080/")
    server.serve_forever()

if __name__ == '__main__':
    run_app()